local qiyi = fk.CreateSkill {
  name = "lingling__qiyi",
  tags = { Skill.Limited },
}

Fk:loadTranslationTable{
  ["lingling__qiyi"] = "起义",
  [":lingling__qiyi"] = "限定技，出牌阶段，你可以令任意名角色各摸三张牌，若这些角色直到各自回合结束皆有造成伤害，你下回合开始时重置此技能。",

  ["#lingling__qiyi"] = "起义：令任意名角色各摸三张牌！",

  ["$lingling__qiyi1"] = "斩木为兵，揭竿为旗！",
  ["$lingling__qiyi2"] = "渔阳一呼，卒移秦祚！"
}

qiyi:addEffect("active", {
  anim_type = "drawcard",
  prompt = "#lingling__qiyi",
  min_target_num = 1,
  card_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(qiyi.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = Util.TrueFunc,
  on_use = function(self, room, effect)
    local player = effect.from
    local targets = table.simpleClone(effect.tos)
    room:sortByAction(targets)
    for _, p in ipairs(targets) do
      if not p.dead then
        p:drawCards(3, qiyi.name)
      end
    end
    if not player.dead then
      room:setPlayerMark(player, qiyi.name, table.map(targets, Util.IdMapper))
    end
  end,
})

qiyi:addEffect(fk.Damage, {
  can_refresh = function (self, event, target, player, data)
    return target == player
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if table.contains(p:getTableMark(qiyi.name), player.id) then
        room:addTableMarkIfNeed(p, "lingling__qiyi_damage", player.id)
      end
    end
  end,
})

qiyi:addEffect(fk.TurnEnd, {
  late_refresh = true,
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room.alive_players) do
      if table.contains(p:getTableMark(qiyi.name), player.id) and
        not table.contains(p:getTableMark("lingling__qiyi_damage"), player.id) then
        room:setPlayerMark(p, qiyi.name, 0)
      end
    end
  end,
})

qiyi:addEffect(fk.TurnStart, {
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark(qiyi.name) ~= 0 and player:getMark("lingling__qiyi_damage") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    if #player:getTableMark(qiyi.name) == #player:getMark("lingling__qiyi_damage") then
      player:setSkillUseHistory(qiyi.name, 0, Player.HistoryGame)
    end
    room:setPlayerMark(player, qiyi.name, 0)
    room:setPlayerMark(player, "lingling__qiyi_damage", 0)
  end,
})

qiyi:addLoseEffect(function (self, player, is_death)
  local room = player.room
  room:setPlayerMark(player, qiyi.name, 0)
  room:setPlayerMark(player, "lingling__qiyi_damage", 0)
end)

return qiyi
